<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2020-05-21 16:27:08
 * @LastEditors: Sam
 * @LastEditTime: 2020-11-30 14:52:12
 */ 
namespace app\admin\model;
use think\Db;
use think\Model;
use traits\ModelTrait;
use basic\BaseModel;

class UserToken extends BaseModel {

    use ModelTrait;


    /**
     * 获取用户token
     * @param [type] $uid
     * @return void
     * @author Sam
     * @date 2020-11-16
     */
    public  static function get_token($uid){
        $token_info = self::where('uid',$uid)->find();
        if(!$token_info){
            //无token
            $new_token = self::create_token($uid);
            self::create([
               'uid' => $uid,
               'token' => $new_token,
               'expire_time' => time()+ 7*24*60*60 //一个星期时间过期
           ]);
           return $new_token;
        }elseif($token_info && time() >= $token_info->expire_time){
            //有token 但是过期
            self::where('uid',$uid)->delete();
            $new_token = self::create_token($uid);
            self::create([
               'uid' => $uid,
               'token' => $new_token,
               'expire_time' => time()+ 7*24*60*60 //一个星期时间过期
           ]);
           return $new_token;
        }else{
            return $token_info->token;
        }
    }

            /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private static function create_token($uid)
    {
        $wxapp_id  = config('wechat.appId');
        // 生成一个不会重复的随机字符串
        // $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt';
        return md5("{$wxapp_id}_{$uid}_{$salt}");
    }
}